import React, { useEffect, useRef, useState } from 'react';

import { marketOfferOrder, marketSelectToken, marketVerifyCode } from './api';
import FlowCustomer from './components/flow_customer';
import ProtocolDialog from './components/protocol_dialog/index';
import { showToast } from './utils';
import enCryp from './utils/enCrypt';

const closeIcon =
  '';

const CAPTCHA_TIME = 60;
let smsFlag = false;
let submitFlag = false;
let tokenFlag = false;
export default function IndexPage(props) {
  const [id, setId] = useState('1');
  // 电话
  const [tel, setTel] = useState('');
  // 验证码
  const [captcha, setCaptcha] = useState('');
  // 验证码显示时间
  const [captchaTime, setCaptchaTime] = useState(0);
  // 加密后的手机号
  const [resultTel, setResultTel] = useState('');
  // 验证码计算时间和timer
  const captchaTimer = useRef({});
  // jdk获取toekn
  const [token, settoken] = useState();

  const [protocolDialogShow, setprotocolDialogShow] = useState(false);
  const [radioCheck, setradioCheck] = useState(false);
  // 显示二确弹窗
  const [showProtocol, setShowProtocol] = useState(false);
  // 显示客服弹窗
  const [showCustomer, setShowCustomer] = useState(false);
  const [confirmDialogShow, setconfirmDialogShow] = useState(false);
  const [vipDialogShow, setvipDialogShow] = useState(false);
  const [orderId, setorderId] = useState('');
  const [codeList] = useState(['XEDdmuDTXS', 'lSY8UggzTn']);

  useEffect(() => {
    window.document.body.style.overflow = showProtocol ? 'hidden' : '';
  }, [showProtocol]);
  useEffect(() => {
    let id = window.location.search;
    if (id) {
      setId(id.split('id=')[1]);
    }
  }, [window.location.search]); // eslint-disable-line
  function startCaptchaTimer() {
    if (captchaTimer.current.timer) {
      clearInterval(captchaTimer.current.timer);
    }
    captchaTimer.current.time = CAPTCHA_TIME;
    captchaTimer.current.timer = setInterval(() => {
      captchaTimer.current.time--;
      setCaptchaTime(captchaTimer.current.time);
      if (captchaTimer.current.time <= 0) {
        clearInterval(captchaTimer.current.timer);
        captchaTimer.current.timer = null;
      }
    }, 1000);
  }

  async function handleSendCaptcha() {
    window.channelSDK().then((d) => getToken());
    if (smsFlag) return;
    let phone = enCryp.Encrypt(tel);
    setResultTel(phone);
    if (captchaTime > 0) return;
    smsFlag = true;
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    }
    try {
      let res = await marketVerifyCode({ phoneNum: tel, goodsCode: codeList[id - 1] });
      if (res.code === 200) {
        startCaptchaTimer();
        setorderId(res.data.orderId);
        showToast(res.data.tipsMsg ?? '发送成功');
      } else {
        if (res.data.tipsMsg) {
          showToast(res.data.tipsMsg ?? '发送失败，请确认是否有办理权限');
        } else {
          showToast(res.msg ?? '发送失败，请确认是否有办理权限');
        }
      }
    } catch (e) {
      showToast(e.message ?? '发送失败，请确认是否有办理权限');
    } finally {
      smsFlag = false;
    }
  }
  // 获取token
  async function getToken() {
    try {
      const res = await marketSelectToken({ data: 'kgj' });
      console.log('res', res);
      if (res.code === 200) {
        settoken(res.data);
      } else {
        showToast(res.msg ?? '获取token失败');
      }
    } catch (error) {
    } finally {
      tokenFlag = false;
    }
  }
  function handleConfirm() {
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    } else if (!captcha) {
      return showToast('请输入验证码');
    } else if (!radioCheck) {
      return showToast('请先同意协议');
    }
    setShowProtocol(true);
  }
  // 最终提交
  const handleNextConfirm = () => {
    if (tokenFlag) return;
    tokenFlag = true;
    setShowProtocol(false);
    handleClick();
    window.location.href =
      'https://dev.coc.10086.cn/coc3/canvas/rightsget-h5-canvas/online/bhqdcw?mobilePhone=' + resultTel;
  };
  // 第二个
  async function handleTwoDialogSuccess() {
    if (submitFlag) return;
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    } else if (!captcha) {
      return showToast('请输入验证码');
    }
    submitFlag = true;
    window.channelSDK().then((d) => getToken());
    try {
      let res = await marketOfferOrder({
        phoneNum: tel,
        goodsCode: codeList[id - 1],
        verifyCode: captcha,
        orderSn: orderId,
        token: token,
      });
      if (res.code === 200) {
        setconfirmDialogShow(true);
        setShowProtocol(false);
      } else {
        showToast(res.data.tipsMsg ?? '办理失败');
      }
    } catch (e) {
      showToast(e.message ?? '办理失败');
    } finally {
      submitFlag = false;
    }
  }
  const handleClick = () => {
    setTel('');
    setCaptcha('');
    setCaptchaTime(0);
    smsFlag = false;
    submitFlag = false;
    tokenFlag = false;
  };

  return (
    <div className="index-page">
      <img className="top-pic" src={`/pic/${id}_top.jpg`} alt="" />
      {/* <img alt="" className="float-customer-btn" src="/pic/pic_4.png" onClick={() => setShowCustomer(!showCustomer)} /> */}
      <div
        className="form-block"
        style={{
          backgroundImage: `url(/pic/${id}_bg.png)`,
          backgroundRepeat: 'no-repeat',
          backgroundSize: 'cover',
        }}
      >
        <div className="prop-line">
          <img className="icon" src="/pic/icon_tel.png" alt="" />
          <input
            className="prop-input"
            placeholder="请输入手机号码（已加密）"
            value={tel}
            id="tellphone"
            onChange={(e) => setTel(e.currentTarget.value)}
          />
        </div>
        <div className="prop-line">
          <img className="icon" src="/pic/icon_captcha.png" alt="" />
          <input
            className="prop-input captcha"
            placeholder="请输入验证码"
            value={captcha}
            id="msgCode"
            onChange={(e) => setCaptcha(e.currentTarget.value)}
          />
          <div id="getCode" className={`btn-captcha ${captchaTime > 0 ? 'disabled' : ''}`} onClick={handleSendCaptcha}>
            {captchaTime > 0 ? captchaTime + 's' : '获取验证码'}
          </div>
        </div>

        <div className="agreement-item">
          <img
            src={`${!radioCheck ? '/pic/icon_radio_default.png' : '/pic/icon_radio_checked.png'}`}
            className="radio-check"
            alt=""
            onClick={() => setradioCheck(!radioCheck)}
          />
          <div>
            <span>我已阅读并同意</span>
            <span className="active-color" onClick={() => setprotocolDialogShow(true)}>
              《中国移动认证服务协议》《个人信息公告》
            </span>
          </div>
        </div>
        <div id="toApply" className="btn-confirm" onClick={handleConfirm}>
          <img src={`./pic/${id}_btn.png`} alt="" />
        </div>
      </div>
      <img alt="" className="top-pic" mode="widthFix" src={`/pic/${id}_dtl.jpg`} />
      {Number(id) === 2 && <img alt="" className="top-pic" mode="widthFix" src={`/pic/${id}_base.jpg`} />}
      <div className={`order-dialog ${showProtocol ? '' : 'd-none'}`}>
        <div className="order-mask" onClick={() => setShowProtocol(false)} />
        <div className="order-center" onClick={() => {}}>
          <img className="img-box" src={`./pic/${id}_dialog.jpg`} alt="" />
          <div className="close-btn" onClick={() => setShowProtocol(false)}>
            <img className="img" src={closeIcon} alt="" />
          </div>
          <div className="tips-block">您的手机{tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}正在订购</div>
          <div className="btn-block">
            <div className="btn" onClick={() => setShowProtocol(false)}>
              我在想想
            </div>
            <div
              id="confirm"
              className="btn confirm-btn"
              onClick={() => {
                handleTwoDialogSuccess();
              }}
            >
              确认订购
            </div>
          </div>
        </div>
      </div>
      {/* 确定订购 */}
      <div className={`order-dialog ${confirmDialogShow ? '' : 'd-none'}`}>
        <div className="order-mask" onClick={() => setconfirmDialogShow(false)} />
        <div
          className="order-center"
          onClick={() => {
            setconfirmDialogShow(false);
            handleNextConfirm();
          }}
        >
          <img className="img-box" src={`./pic/${id}_ok.png`} alt="" />
          <div
            className="close-btn"
            onClick={(e) => {
              e.stopPropagation();
              setconfirmDialogShow(false);
              setvipDialogShow(true);
            }}
          >
            <img className="img" src={closeIcon} alt="" />
          </div>
        </div>
      </div>
      {/* 权益领取弹窗 */}
      <div className={`protocol-dialog ${vipDialogShow ? '' : 'd-none'}`}>
        <div className="protocol-mask" onClick={() => setvipDialogShow(false)} />
        <div className="protocol-center" onClick={() => setvipDialogShow(false)}>
          <img src="./pic/1_qy.png" alt="" />
        </div>
      </div>

      {protocolDialogShow ? <ProtocolDialog onClose={() => setprotocolDialogShow('')} /> : null}

      {showCustomer ? <FlowCustomer tel="15238380662" onClose={() => setShowCustomer(false)} /> : null}
    </div>
  );
}
